import os
import time
import traceback
from time import strftime

import pymysql
import yaml
from apscheduler.schedulers.blocking import BlockingScheduler
from fernet import Fernet
from pymysql.cursors import DictCursor

from wxauto import WeChat

# 正式上线需要修改这个密码
YML_PATH = "conf/application.yml"
# 加密密码
KEY = b'kc7aV67sn-Cmb0_qak5E1lJoDjxRJbdP4c0UL8XGjPc='
# 默认群名
DEFAULT_QUNM = "龙龙机器人预警群"
# 间隔时间
TIME_SLEEP = 5


# 读取yml 配置文件
def read_yaml(filename: str = YML_PATH):
    if not os.path.exists(filename):
        raise FileNotFoundError(f"File {filename} not found")
    with open(filename, "r", encoding="utf-8") as f:
        config = yaml.safe_load(f.read())
        return config


# 对称数据解密
def decrypt_data(data):
    if data is None or data == '':
        return ""
    # 使用秘钥创建一个Fernet对象
    cipher_suite = Fernet(KEY)
    decrypted = cipher_suite.decrypt(data.encode('utf-8')).decode('utf-8')
    return decrypted


def do_job(ldxt99_db, ldxt99_db_cursor):
    # 查询机构和群名对照表
    sql = "select * from jg_qunm_ys"
    ldxt99_db_cursor.execute(sql)
    jg_qunm_list = ldxt99_db_cursor.fetchall()

    # 昨天当天日期获取
    today = strftime("%Y-%m-%d", time.localtime())
    # 查询机构和群名对照表
    sql = "select * from sys_deploy_log where deploy_date = %s"
    ldxt99_db_cursor.execute(sql, today)
    deploy_log_list = ldxt99_db_cursor.fetchall()

    content = ""
    for log in deploy_log_list:
        content = content + log["content"]  + "\n"

    # 发送数据到微信群中
    wx = WeChat()

    # 发送所有数据到微信客户端
    for jgqunm in jg_qunm_list:
        try :
            who = jgqunm["qunm"]
            wx.SendMsg(content, who)
        except Exception as e:
            print("发生错误：", str(e))
            print("堆栈信息如下：")
            print(traceback.format_exc())

        time.sleep(TIME_SLEEP)



def start_job():
    # 读取ftp mysql 等配置文件
    config = read_yaml(YML_PATH)

    # 连接mysql 数据源
    ldxt99_druid = config["druid"]["ldxt99"]
    # 解密数据库密码
    passwd = decrypt_data(ldxt99_druid["passwd"])
    ldxt99_db = pymysql.connect(
        host=ldxt99_druid["host"],
        port=ldxt99_druid["port"],
        user=ldxt99_druid["user"],
        passwd=passwd,
        database=ldxt99_druid["database"]
    )
    ldxt99_db_cursor = ldxt99_db.cursor(cursor=DictCursor)

    try:
        print("开始执行:" + strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
        do_job(ldxt99_db, ldxt99_db_cursor)
    except Exception as e:
        print("发生错误：", str(e))
        print("堆栈信息如下：")
        print(traceback.format_exc())
    finally:
        ldxt99_db.close()
        ldxt99_db_cursor.close()
        print("结束执行:" + strftime("%Y-%m-%d %H:%M:%S", time.localtime()))

if __name__ == "__main__":
    start_job()
    schedule = BlockingScheduler()
    schedule.add_job(func=start_job, trigger='cron', hour=1, minute=0, second=0, misfire_grace_time=60)

    schedule.start()